/*
 * @Author: 230800029 rixing.liu@hytera.com
 * @Date: 2024-04-19 11:52:39
 * @LastEditors: 230800029 rixing.liu@hytera.com
 * @LastEditTime: 2024-04-19 13:11:16
 * @FilePath: /vue3-pg/src/components/menu/use-sub-tree.ts
 * @Description: 
 * Copyright (c) 2024 by rixing.liu, All Rights Reserved.
 */
import { computed } from 'vue';
import { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import appClientMenus from '@/rotuer/appClientMenus.ts';
import { cloneDeep } from 'lodash-es';

export default function useMenuTree() {
  const appRoute = appClientMenus;
  const menuTree = computed(() => {
    const copyRouter = cloneDeep(appRoute) as RouteRecordNormalized[];
    
    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null;

      const collector: any = _routes.map((element) => {
       

        // leaf node
        if (element.meta?.hideChildrenInMenu || !element.children) {
          element.children = [];
          return element;
        }

        // route filter hideInMenu true
        element.children = element.children.filter(
          (x) => x.meta?.hideInMenu !== true
        );

        // Associated child node
        const subItem = travel(element.children, layer + 1);

        if (subItem.length) {
          element.children = subItem;
          return element;
        }
        // the else logic
        if (layer > 1) {
          element.children = subItem;
          return element;
        }

        if (element.meta?.hideInMenu === false) {
          return element;
        }

        return null;
      });
      return collector.filter(Boolean);
    }
    return travel(copyRouter, 0);
  });

  return {
    menuTree,
  };
}
